package queue;

/**
 * @author zhaoziqiang
 * @Description:
 * @date 2020/8/18 20:36
 */
public class LoopQueue<E> implements Queue<E> {
    private E[] data;
    private int head, tail, size;

    public LoopQueue(int capacity) {
        data = (E[])new Object[capacity + 1];
        head = 0;
        tail = 0;
        size = 0;
    }

    public LoopQueue() {
        this(10);
    }

    @Override
    public void enqueue(E e) {
        if ((tail + 1) % data.length == head)//队列已满
            resize(getCapacity() * 2);
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[])new Object[newCapacity + 1];
        for (int i = 0; i < size; i++) {
            newData[i] = data[(i + head) % data.length];
        }
        data = newData;
        head = 0;
        tail = size;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public int getCapacity() {
        return data.length - 1;
    }

    @Override
    public E dequeue() {
        if (isEmpty())
            throw new IllegalArgumentException("Cannot dequeue an element form an empty queue");
        E temp = data[head];
        data[head] = null;
        head = (head + 1) % data.length;
        size--;
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0)
            resize(getCapacity() / 2);
        return temp;
    }

    @Override
    public E getHead() {
        return data[head];
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Queue: size=" + size + ";" + "Capacity=" + getCapacity() + "\n");
        sb.append("head [");
        for (int i = head; i != tail; i = (i + 1) % data.length) {
            sb.append(data[i]);
            if ((i + 1) % data.length != tail)
                sb.append(",");

        }
        sb.append("]");
        sb.append(" tail");
        return sb.toString();
    }

    public static void main(String[] args) {

        LoopQueue<Integer> queue = new LoopQueue<>();
        for (int i = 0; i < 10; i++) {
            queue.enqueue(i);
            System.out.println(queue);
            if (i % 3 == 2) {
                System.out.println("i="+i+"----------i%3="+i%3);
                queue.dequeue();
                System.out.println(queue);
            }

        }

    }
}
